package com.example.accessibilitydemo.service;

import java.util.List;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.PendingIntent;
import android.os.Build;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.example.accessibilitydemo.common.Constants;

public class QiangHongBaoService extends AccessibilityService {

	private static final String TAG = QiangHongBaoService.class.getName();

	@Override
	public void onAccessibilityEvent(AccessibilityEvent event) {
		// 接收事件,如触发了通知栏变化、界面变化等
		int eventType = event.getEventType();
		// 通知栏事件
		switch (eventType) {
		case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:// 通知栏出现新信息
			Log.i(TAG, "有新消息了");
			openNotify(event);
			break;
		case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:// 窗口改变，如果是聊天界面，则调动打开红包
			Log.i(TAG, "窗口发生了变化");
			openHongBao(event);
			break;
		default:
			break;
		}
	}

	@Override
	public void onInterrupt() {
		// 服务中断，如授权关闭或者将服务杀死

	}

	@Override
	protected void onServiceConnected() {
		AccessibilityServiceInfo info = new AccessibilityServiceInfo();
		// 需要响应的事件类型
		// 此处为通知栏变化事件、界面变化事件
		info.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED
				| AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
		// 如不指定包名，则此服务对所有应用有效
		// 此处指定微信包名
		info.packageNames = new String[] { Constants.WECHAT_PACKAGENAME };
		// 设置使用的反馈类型
		// 此处设为通用类型
		info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
		// 设置响应时间
		info.notificationTimeout = 100;
		// 应用参数
		this.setServiceInfo(info);
	}

	/**
	 * 打开通知栏消息
	 */
	private void openNotify(AccessibilityEvent event) {
		// 获取通知栏信息内容
		List<CharSequence> texts = event.getText();
		// 检查是否有红包信息
		if (!texts.isEmpty()) {
			for (CharSequence t : texts) {
				String text = String.valueOf(t);
				if (text.contains("[微信红包]")) {
					openWeixin(event);
					break;
				}
			}
		}
	}

	/**
	 * 打开微信
	 * 
	 * @param event
	 */
	public void openWeixin(AccessibilityEvent event) {
		if (event.getParcelableData() == null || !(event.getParcelableData() instanceof Notification)) {
			return;
		}
		// 将微信的通知栏消息打开
		// 获取Notification对象
		Notification notification = (Notification) event.getParcelableData();

		String content = notification.tickerText.toString();
		String[] msg = content.split(":");
		String name = msg[0].trim();
		String text = msg[1].trim();
		Log.i(TAG, "有新消息了,name:" + name + ",text:" + text);
		// 调用其中的PendingIntent，打开微信界面
		PendingIntent pendingIntent = notification.contentIntent;
		try {
			pendingIntent.send();
		} catch (Exception e) {
			Log.i(TAG, "openWeixin throw exception:" + e.getMessage());
		}
	}

	/**
	 * 打开微信后，判断是什么界面，并做相应的动作
	 */
	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
	private void openHongBao(AccessibilityEvent event) {
		if (Constants.WECHAT_LUCK_MONEY_RECEIVER_CLASS.equals(event.getClassName())) {
			// 拆红包界面(拆红包)
			// com.tencent.mm:id/b9m
			// com.tencent.mm:id/bi3
			clickById("com.tencent.mm:id/bi3");
		} else if (Constants.WECHAT_LUCK_MONEY_DETAIL_CLASS.equals(event.getClassName())) {
			// 拆完红包后，看红包金额的界面,返回
			// performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
		} else if (Constants.WECHAT_LAUNCHER.equals(event.getClassName())) {
			// 聊天界面,打开最新的那个红包(领取红包)
			openLastPacket();
		}
	}

	/**
	 * 在聊天界面中点红包
	 */
	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
	private void openLastPacket() {
		AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
		try {
			if (nodeInfo == null) {
				return;
			}

			// 找到领取红包的点击事件
			List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByText("领取红包");
			// 最新的红包领,通过调试可知[领取红包]是text，本身不可被点击，用getParent()获取可被点击的对象

			AccessibilityNodeInfo parent = list.get(list.size() - 1);
			// 谷歌重写了toString()方法，不能用它获取ClassName@hashCode串
			while (parent != null) {
				if (parent.isClickable()) {
					parent.performAction(AccessibilityNodeInfo.ACTION_CLICK);
					break; // 只领最新的一个红包
				}
				parent = parent.getParent();
			}
		} catch (Exception e) {
			Log.i(TAG, "openLastPacket throw exception:" + e.getMessage());
		}

	}

	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
	private void clickById(String viewId) {
		AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
		try {
			if (nodeInfo == null) {
				return;
			}

			List<AccessibilityNodeInfo> nodes = nodeInfo.findAccessibilityNodeInfosByViewId(viewId);
			for (AccessibilityNodeInfo node : nodes) {
				if (node.isClickable())
					node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
			}
		} catch (Exception e) {
			Log.i(TAG, "clickById throw exception:" + e.getMessage());
		}
	}

}
